// pages/topicality/zhuanti/zhuanti.js
const app = getApp()
const util = require("../../../utils/util.js");
var QQMapWX = require('../../../utils/qqmap-wx-jssdk1.2/qqmap-wx-jssdk.min.js');
var qqmapsdk = new QQMapWX({
    key: 'KR7BZ-XSQ3P-VGFD7-LNRZL-E7PXE-STF76'
});

Page({

    /**
     * 页面的初始数据
     */
    data: {
        citycode: "hz",
        city: '杭州',
        province: '浙江',
        pindex: 0,
        cindex: 0,
        cityPick: ["选择城市"],

        showtk: false,
        showNav: true, // 快捷导航是否展开
        showShare: true, // 显示分享按钮

        menuIndex: 0,
        rukouIndex: 0,
        titleIndex: 0,
        needSubscribeMessage: false,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        var sceneData = [];
        if (options.scene != undefined) {
            var scene = decodeURIComponent(options.scene);
            var arrPara = scene.split("/");
            for (var i in arrPara) {
                sceneData.push(arrPara[i])
            }
        }
        this.setData({
            citycode: sceneData[0] ? sceneData[0] : (options.city ? options.city : this.data.citycode),
            action: sceneData[1] ? sceneData[1] : (options.action ? options.action : ''),
        });
        this.setData({
            needSubscribeMessage: util.getName(this.data.action),
        });
        util.getUrl(app.globalData.url).then((res) => {
            this.getProvinceData(this.data.citycode);
        })

      
    },

    // 获取定位
    getLocation() {
        qqmapsdk.reverseGeocoder({
            success: (res) => {
                let city = res.result.address_component.city;
                // let city="芜湖市";
                let citydata = this.data.citylist.filter(v => {
                    if (city.indexOf(v.cityname) != -1) {
                        return v;
                    }
                });

                if (citydata != '' && city.indexOf(this.data.city) == -1) {
                    // wx.showModal({
                    //     content: '您当前定位城市为' + city + '\n是否需要切换到' + city,
                    //     success: res => {
                    //         if (res.confirm) {
                                this.setData({
                                    city: Array.isArray(citydata) ? citydata[0].cityname : this.data.city,
                                    citycode: Array.isArray(citydata) ? citydata[0].citycode : this.data.citycode,
                                    province: Array.isArray(citydata) ? citydata[0].province : this.data.province,
                                    cityPick: ["选择城市"]
                                })
                                let clist = [];
                                this.data.provPick.forEach((v, k) => {
                                    if (v == this.data.province) {
                                        this.setData({
                                            pindex: k,
                                        })
                                    }
                                })
                                this.data.cityArray[this.data.pindex].citylist.forEach(v => {
                                    clist.push(v.cityname)
                                })
                                this.setData({
                                    cityPick: this.data.cityPick.concat(clist)
                                })
                                this.data.cityPick.forEach((v, k) => {
                                        if (v == this.data.city) {
                                            this.setData({
                                                cindex: k,
                                            })
                                        }
                                    })
                                    // 获取城市公众号二维码
                                this.getQrcode(this.data.citycode);
                                this.getInfoData(this.data.citycode);
                    //         }
                    //     }
                    // })
                }

            },
        });
    },

    // 获取城市公众号二维码
    getQrcode(citycode) {
        util.cityConfig(citycode).then(res => {
            this.setData({
                qrcodeimg: res.qrcode,
            })
        })
    },

    // 获取城市
    getProvinceData(optcode) {
        let data = {
            action: this.data.action,
            type: "city",
        };
        util.request('zhuanti_all.php', data,'POST' ).then(res => {
            this.setData({
                cityArray: res.data.data.city,
            })
            let provPick = [];
            let citylist = [];
            let clist = [];
            this.data.cityArray.forEach(v => {
                v.citylist.forEach(v => {
                    citylist.push(v)
                })
                provPick.push(v.province)
                this.setData({
                    provPick,
                    citylist
                })
            })
            if (this.data.citylist) {
                this.data.citylist.forEach((v, k) => {
                    if (optcode == v.citycode) {
                        this.setData({
                            citycode: v.citycode,
                            city: v.cityname,
                            province: v.province,
                        })
                    } else {
                        this.setData({
                            citycode: this.data.citycode,
                            city: this.data.city,
                            province: this.data.province,
                        })
                    }
                })
            }

            this.data.provPick.forEach((v, k) => {
                if (v == this.data.province) {
                    this.setData({
                        pindex: k,
                    })
                }
            })

            this.data.cityArray[this.data.pindex].citylist.forEach(v => {
                clist.push(v.cityname)
            })
            this.setData({
                cityPick: this.data.cityPick.concat(clist)
            })

            this.data.cityPick.forEach((v, k) => {
                    if (v == this.data.city) {
                        this.setData({
                            cindex: k,
                        })
                    }
                })
                // 获取城市公众号二维码
            this.getQrcode(this.data.citycode);
            this.getInfoData();
            if (this.data.citylist != "" && Array.isArray(this.data.citylist)) {
                // 获取定位
                this.getLocation();
            }

        })
    },

    getInfoData(citycode) {
        let data = {
            action: this.data.action,
            type: "city",
            citycode: citycode ? citycode : this.data.citycode
        };
        util.request('zhuanti_all.php', data, 'POST').then(res => {
       
          this.selectComponent("#fangyiTools").getTools(this.data.cityCode)
            let infodata = res.data.data;
            if (res.data.data.daofen) {
                res.data.data.daofen.content = res.data.data.daofen.content
                    .replace(/<p([\s\w"=\/\.:;]+)((?:(="[^"]+")))/ig, '<p')
                    .replace(/<p([\s\w"=\/\.:;]+)((?:(style="[^"]+")))/ig, '<p')
                    .replace(/<p([\s\w"=\/\.:;]+)((?:(class="[^"]+")))/ig, '<p')
                    .replace(/<p>/ig, '<p class="p_class">')
                    .replace(/<img([\s\w"-=\/\.:;]+)((?:(style="[^"]+")))/ig, '<img$1')
                    .replace(/<img/gi, '<img style="width:100%;height:auto"')
                    // .replace(/<span>/ig, '<p class="p_class">')
            }
            wx.setNavigationBarTitle({
                title: res.data.data.title
            })

            if (infodata.list) {
                infodata.list.forEach((item, index) => {
                    if (item.hasOwnProperty("model"))
                        item.model.forEach((v, k) => {
                            if ((v.name === "rukou") && v.data) {
                                v.data.forEach((m, n) => {
                                    if (n == 0) {
                                        m.checked = true;
                                    } else {
                                        m.checked = false;
                                    }
                                })
                            } else if (v.name === "multirukou" && v.data) {
                                v.data.forEach((item) => {
                                    if (item.list)
                                        item.list.forEach((rukou, rukouindex) => rukou.checked = rukouindex == 0 ? true : false);
                                });
                            } else if (v.name === "article" && v.data) {
                                if (v.data.length > 3) {
                                    this.articleList = JSON.parse(JSON.stringify(v.data));
                                    v.data = v.data.splice(0, 3);
                                    v.more = true;
                                }
                            }
                        });
                })
            }

            this.setData({
                infoData: res.data.data,
                // lunbotu: res.data.data.lunbotu,
                // func: res.data.data.func,
                // multifunc: res.data.data.multifunc,
                // rukou: res.data.data.rukou,
                modelData: res.data.data.list,
                keywords: res.data.data.keyword,
                daofen: res.data.data.daofen
            });
            util.reportMessage("fangwenliang", { action: this.data.infoData.name })

            this.getzixunData(this.data.keywords[0])
        })
    },

    moreArticle(e) {
        this.data.modelData.forEach((item)=>{
            if (item.model[0].name=='article'&&item.model[0].data) {
               if ( JSON.stringify(item.model[0].data.sort()) == JSON.stringify(e.currentTarget.dataset.arr.sort())) {
                    item.model[0].more = false;
                    item.model[0].data = this.articleList;
               }
            }
        })
        this.setData({
            modelData: this.data.modelData,
        });
    },

    // 省份选择
    bindProv: function(e) {
        this.setData({
            pindex: e.detail.value,
            cindex: 0,
            cityPick: ["选择城市"],
        })
        let clist = [];
        this.data.cityArray[this.data.pindex].citylist.forEach(v => {
            clist.push(v.cityname)
        })
        this.setData({
            cityPick: this.data.cityPick.concat(clist),
        })
    },

    // 省份选择
    bindProv: function(e) {
        this.setData({
            pindex: e.detail.value,
            cindex: 0,
            cityPick: ["选择城市"],
        })
        let clist = [];
        this.data.cityArray[this.data.pindex].citylist.forEach(v => {
            clist.push(v.cityname)
        })
        this.setData({
            cityPick: this.data.cityPick.concat(clist),
        })
    },

    // 城市选择
    bindCity(e) {
        this.setData({
            cindex: e.detail.value
        })
        let cityname = this.data.cityPick[this.data.cindex];
        if (this.data.citylist) {
            this.data.citylist.forEach(v => {
                if (v.cityname == cityname) {
                    let citycode = v.citycode;
                    this.setData({
                        citycode,
                        city: cityname
                    })
                }
            })
        }
        // 获取城市公众号二维码
        this.getQrcode(this.data.citycode);
        this.getInfoData(this.data.citycode);
    },

    // 功能类（多项切换）菜单点击
    menuClick(e) {
        let menuIndex = e.currentTarget.dataset.index;
        this.setData({
            menuIndex
        })
    },

    multiRukou(e) {
        let rukouIndex = e.currentTarget.dataset.index;
        this.setData({
            rukouIndex
        })
    },

    navDetail(e) {
        let id = e.currentTarget.dataset.id;
        let citycode = e.currentTarget.dataset.citycode;
        let url = e.currentTarget.dataset.url;
        let type = e.currentTarget.dataset.type;
        let title = e.currentTarget.dataset.title;
        if (id && id != 0) {
            wx.navigateTo({
                url: '/pages/article/detail/detail?id=' + id + '&type=' + type + '&city=' + (citycode ? citycode : this.data.citycode),
            })
        } else {
            if (url) {
                if (url.indexOf("mp.weixin.qq.com") != -1) {
                    wx.navigateTo({
                        url: '/pages/webview/webview?path=' + encodeURIComponent(url),
                    })
                } else {
                    this.setData({
                        showtk: true
                    })
                    util.navContact(title, url)
                }
            }

        }
    },

    // 入口展开收起
    rukouChecked(e) {
        let name = e.currentTarget.dataset.name;
        let checked = e.currentTarget.dataset.checked;
        this.data.modelData.forEach((item, index) => {
            if (item.hasOwnProperty("model") && Array.isArray(item.model))
                item.model.forEach((v, k) => {
                    if (v.name === "rukou") {
                        if (v.data){
                            v.data.forEach((m, n) => {
                                if (name == n) {
                                    m.checked = !checked
                                }
                            })
                        }
                    }
                })
        })
        this.setData({
            modelData: this.data.modelData,
        })
    },

    moreRukouChecked(e) {

        let index = e.currentTarget.dataset.index;
        let checked = e.currentTarget.dataset.checked;
        try {
            if (this.data.modelData[1] && this.data.modelData[1].hasOwnProperty("model"))
                this.data.modelData[1].model[0].data[this.data.rukouIndex].list[index].checked = !checked;
        } catch (err) {

        }
        // this.data.modelData.forEach((item, index) => {
        //     item.model.forEach((v, k) => {
        //         if (v.name === "multirukou") {
        //             v.data.forEach((m, n) => {
        //                 if (m.list)
        //                     m.list.forEach((item, idx) => {
        //                         if (idx != index)
        //                             item.checked = false;
        //                     });
        //             });
        //         }
        //     });
        // });
        this.setData({
            modelData: this.data.modelData,
        })
    },

    zxtitleBtn(e) {
        let keywords = e.currentTarget.dataset.title;
        let titleIndex = e.currentTarget.dataset.index;
        this.setData({
            titleIndex
        })
        this.getzixunData(keywords)
    },

    // 获取资讯
    getzixunData(keywords) {
        util.inforMation(this.data.citycode, keywords).then((res) => {
            this.setData({
                articleData: res
            })
        })
    },

    // 进入客服会话
    contact() {
        this.setData({
            showtk: false,
        })
    },

    // 关闭
    close() {
        this.setData({
            showtk: false,
        })
    },

    /**
     * 页面滑动事件的处理函数
     */
    onPageScroll: function(e) {
        this.setData({
            showNav: false,
        })
    },



    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {
        return {
            title: this.data.infoData ? this.data.infoData.title : "专题",
        }
    },

    // 分享朋友圈
    onShareTimeline: function() {
        return {
            title: this.data.infoData ? this.data.infoData.title : "专题",
            imageUrl: "http://imgbdb3.bendibao.com/xcx/20205/20/2020520151108_56661.jpg",
            query: {
                city: this.data.citycode,
                action: this.data.action
            },
        }
    },
})